/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.func;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.result.DirectJsonResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.service.common.MetaBeanService;
import com.je.meta.service.func.MetaFuncRelyonService;
import com.je.meta.service.table.MetaResColumnService;
import com.je.meta.service.table.MetaTableColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/je/meta/resColumn")
public class ResColumnController extends AbstractPlatformController {

    @Autowired
    private MetaResColumnService resColumnService;
    @Autowired
    private MetaFuncRelyonService funcRelyonService;
    @Autowired
    private MetaBeanService metaBeanService;
    @Autowired
    private MetaTableColumnService metaTableColumnService;

    /**
     * 获取关联字段
     */
    @RequestMapping(value = "/getRelevanceField", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult getRelevanceField(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = new DynaBean();
        //参考字段
        dynaBean.setStr("consultFields",getStringParameter(request,"consultFields"));
        //目标功能ID
        dynaBean.setStr("targetFuncId",getStringParameter(request,"targetFuncId"));
        Map<String,Object> result = resColumnService.getRelevanceField(dynaBean);
        return BaseRespResult.successResult(result);
    }


    /**
     * 列表更新
     */
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        String strData = param.getStrData();
        int count = resColumnService.doUpdateList(strData);
        String funcId = getStringParameter(request,"funcId");
        resColumnService.batchSortOutColumnInfoByFuncId(funcId);
        return BaseRespResult.successResult(count + "条记录被更新!");
    }

    /**
     * 导入字段
     *
     * @param param
     */
    @RequestMapping(value = "/impl", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult impl(BaseMethodArgument param, HttpServletRequest request) {
        String funcId = getStringParameter(request, "RESOURCECOLUMN_FUNCINFO_ID");
        DynaBean fun = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId);
        String errors = resColumnService.impl(fun);
        //处理导入软连接操作
        funcRelyonService.doImpl(funcId);
        if (StringUtil.isNotEmpty(errors)) {
            return BaseRespResult.errorResult(errors);
        }
        resColumnService.batchSortOutColumnInfoByFuncId(funcId);
        return BaseRespResult.successResult(null, "导入成功!");
    }

    /**
     * 同步字段
     *
     * @param param
     */
    @RequestMapping(value = "/doSync", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doSync(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = new DynaBean();
        String resourcecolumnFuncinfoId = getStringParameter(request, "RESOURCECOLUMN_FUNCINFO_ID");
        dynaBean.setStr("RESOURCECOLUMN_FUNCINFO_ID", resourcecolumnFuncinfoId);
        dynaBean.setStr("RESOURCECOLUMN_PLAN_ID", getStringParameter(request, "RESOURCECOLUMN_PLAN_ID"));
        dynaBean.setStr("RESOURCEFIELD_PLAN_ID", getStringParameter(request, "RESOURCEFIELD_PLAN_ID"));
        resColumnService.doSync(dynaBean);
        /**
         * 此代码目的不明确，先注释
         */
        //funcRelyonService.doSyncField(dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID"));
        return BaseRespResult.successResult(null, "同步成功!");
    }

    /**
     * 传入字段类型校验
     *
     * @param param
     */
    @RequestMapping(value = "/doSave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doSave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String xtype = dynaBean.getStr("RESOURCECOLUMN_XTYPE");

        if (!"displayfield".equals(xtype) && !"morecolumn".equalsIgnoreCase(xtype) && !"actioncolumn".equalsIgnoreCase(xtype) && !"markcolumn".equalsIgnoreCase(xtype) && !"postilcolumn".equalsIgnoreCase(xtype) && !"funceditcolumn".equalsIgnoreCase(xtype)) {
            return BaseRespResult.errorResult(MessageUtils.getMessage("function.column.type.error"));
        }
        resColumnService.buildDefault(dynaBean);
        if ("funceditcolumn".equals(xtype)) {
            String funcId = dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID", "");
            DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", funcId, "JE_CORE_FUNCINFO_ID,FUNCINFO_TABLENAME");
            DynaBean table = metaBeanService.getResourceTable(funcInfo.getStr("FUNCINFO_TABLENAME"));
            if ("VIEW".equals(table.getStr("RESOURCETABLE_TYPE"))) {
                return BaseRespResult.errorResult("视图不可以加入编辑标记！");
            }
            long haveCount = metaService.countBySql(ConditionsWrapper.builder().table("JE_CORE_TABLECOLUMN")
                    .apply("TABLECOLUMN_RESOURCETABLE_ID={0} AND TABLECOLUMN_CODE='SY_FUNCEDIT'", table.getStr("JE_CORE_RESOURCETABLE_ID")));
            if (haveCount <= 0) {
                DynaBean field = new DynaBean("JE_CORE_TABLECOLUMN", true);
                field.set("TABLECOLUMN_NAME", "编辑标记");
                field.set("TABLECOLUMN_CODE", "SY_FUNCEDIT");
                field.set("TABLECOLUMN_OLDCODE", "SY_FUNCEDIT");
                field.set("TABLECOLUMN_UNIQUE", "0");
                field.set("TABLECOLUMN_OLDUNIQUE", "0");
                field.set("TABLECOLUMN_TYPE", "VARCHAR30");
                field.set("TABLECOLUMN_TREETYPE", "NORMAL");
                field.set("TABLECOLUMN_TABLECODE", table.getStr("RESOURCETABLE_TABLECODE"));
                field.set("TABLECOLUMN_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID"));
                field.set("TABLECOLUMN_ISNULL", "1");
                field.set("TABLECOLUMN_ISCREATE", "0");
                field.set("TABLECOLUMN_CLASSIFY", "SYS");
                field.set("SY_STATUS", "1");
                field.set("SY_ORDERINDEX", 327);
                commonService.buildModelCreateInfo(field);
                metaTableColumnService.addField(field);
            }
            DynaBean inserted = metaService.selectOne("JE_CORE_RESOURCECOLUMN",
                    ConditionsWrapper.builder().apply("RESOURCECOLUMN_FUNCINFO_ID={0} AND RESOURCECOLUMN_CODE='SY_FUNCEDIT'", dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID")));
            if (inserted == null) {
                dynaBean.set("RESOURCECOLUMN_XTYPE", "uxcolumn");
            }
        }

        //校验协作/标记/编辑列 是否重复
        if ("SY__POSTIL,SY_FUNCEDIT,SY__MARK".contains(dynaBean.getStr("RESOURCECOLUMN_CODE"))) {
            long count = metaService.countBySql(ConditionsWrapper.builder().table("JE_CORE_RESOURCECOLUMN")
                    .eq("RESOURCECOLUMN_FUNCINFO_ID", dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID")).eq("RESOURCECOLUMN_CODE", dynaBean.getStr("RESOURCECOLUMN_CODE")));
            if (count > 0) {
                return BaseRespResult.errorResult("只能添加一个" + dynaBean.getStr("RESOURCECOLUMN_NAME") + "列！");
            }
        }

        //保存功能列
        commonService.doSave(dynaBean);
        funcRelyonService.doSave("JE_CORE_RESOURCECOLUMN", dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID"), dynaBean);
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * 更换字段名
     *
     * @param param
     */
    @RequestMapping(value = "/doQuerySave", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doQuerySave(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String funId = dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID");
        String name = dynaBean.getStr("RESOURCECOLUMN_NAME");
        String code = dynaBean.getStr("RESOURCECOLUMN_CODE");
        long count = metaService.countBySql(ConditionsWrapper.builder().table("JE_CORE_RESOURCECOLUMN")
                .apply("RESOURCECOLUMN_FUNCINFO_ID={0} and RESOURCECOLUMN_CODE={1}", funId, code));
        if (count > 0) {
            return BaseRespResult.errorResult("该列名已使用，请更换字段名!");
        }
        DynaBean rc = new DynaBean("JE_CORE_RESOURCECOLUMN", false);
        rc.set("RESOURCECOLUMN_FUNCINFO_ID", funId);
        rc.set("RESOURCECOLUMN_CODE", code);
        rc.set("RESOURCECOLUMN_NAME", name);
        rc.set("RESOURCECOLUMN_NAME_EN", "");
        //将导入的字段标识为true
        rc.set("RESOURCECOLUMN_IFIMPL", "1");
        //是否快速查询 false
        rc.set("RESOURCECOLUMN_QUICKQUERY", "0");
        //默认序号为0
        rc.set("SY_ORDERINDEX", 0);
        //设置默认宽度为80
        rc.set("RESOURCECOLUMN_WIDTH", "80");
        //是否拥有转换器conversion
        rc.set("RESOURCECOLUMN_CONVERSION", "0");
        //是否拥有转换器highlighting
        rc.set("RESOURCECOLUMN_HIGHLIGHTING", "0");
        //是否超链接hyperLink
        rc.set("RESOURCECOLUMN_HYPERLINK", "0");
        //是否在字典中取
        rc.set("RESOURCECOLUMN_ISDD", "0");
        //合并单元格      否
        rc.set("RESOURCECOLUMN_MERGE", "0");
        //锁定列
        rc.set("RESOURCECOLUMN_LOCKED", "");
        //多表头   否
        rc.set("RESOURCECOLUMN_MORECOLUMN", "0");
        //启用图标
        rc.set("RESOURCECOLUMN_ENABLEICON", "0");
        //启用分步加载
        rc.set("RESOURCECOLUMN_LAZYLOAD", "0");
        rc.set("RESOURCECOLUMN_ALIGN", "left");
        //排序
        rc.set("RESOURCECOLUMN_ORDER", "0");
        //索引
        rc.set("RESOURCECOLUMN_INDEX", "0");
        //是否主键
        rc.set("RESOURCECOLUMN_ISPK", "0");
        rc.set("RESOURCECOLUMN_SYSMODE", "CP");
        /**---------------------如果有初始化信息则使用初始化信息存储------------------------------------*/
        //是否可以为空  true
        rc.set("RESOURCECOLUMN_ALLOWBLANK", "1");
        rc.set("RESOURCECOLUMN_QUERYTYPE", "no");
        //改动：判断是否包含NAME和CODE 张帅鹏
        rc.set("RESOURCECOLUMN_HIDDEN", "0");
        rc.set("RESOURCECOLUMN_LAZYLOAD", "1");
        //字段类型  默认为无  不可编辑
        rc.set("RESOURCECOLUMN_XTYPE", "uxcolumn");
        //列表编辑   默认为否
        rc.set("RESOURCECOLUMN_ALLOWEDIT", "0");
        rc.set("RESOURCECOLUMN_DESCRIPTION", "");
        rc.set("SY_FLAG", "1");
        JSONObject otherConfig = new JSONObject();
        otherConfig.put("noWhereSql", "1");
        rc.set("RESOURCECOLUMN_OTHERCONFIG", otherConfig.toString());
        commonService.buildModelCreateInfo(rc);
        metaService.insert(rc);
        long fieldCount = metaService.countBySql(ConditionsWrapper.builder().table("JE_CORE_RESOURCEFIELD")
                .apply("RESOURCEFIELD_FUNCINFO_ID={0} and RESOURCEFIELD_CODE={1}", funId, code));
        if (fieldCount <= 0) {
            DynaBean rf = new DynaBean("JE_CORE_RESOURCEFIELD", false);
            rf.set(BeanService.KEY_PK_CODE, "JE_CORE_RESOURCEFIELD_ID");
            rf.set("RESOURCEFIELD_FUNCINFO_ID", funId);
            rf.set("RESOURCEFIELD_CODE", code);
            rf.set("RESOURCEFIELD_NAME", name);
            rf.set("RESOURCEFIELD_NAME_EN", "");
            //将导入的字段标识为true
            rf.set("RESOURCEFIELD_IFIMPL", "1");
            //是否可用  true
            rf.set("RESOURCEFIELD_DISABLED", "1");
            //是否可以为空  true
            rf.set("RESOURCEFIELD_ALLOWBLANK", "1");
            //可选可编辑   默认否
            rf.set("RESOURCEFIELD_EDITABLE", "0");
            //所占列数
            rf.set("RESOURCEFIELD_COLSPAN", 1);
            //数值型
            //字段类型   默认为文本框
            rf.set("RESOURCEFIELD_XTYPE", "textfield");
            //是否只读
            rf.set("RESOURCEFIELD_READONLY", "1");
            rf.set("RESOURCEFIELD_HIDDEN", "0");
            //根据列的添加方式 字典添加，表添加来快速初始化功能配置项
            //默认序号为0
            rf.set("SY_ORDERINDEX", 0);
            //所占行数
            rf.set("RESOURCEFIELD_ROWSPAN", 1);
            rf.set("RESOURCEFIELD_SYSMODE", "CP");
            rf.set("RESOURCEFIELD_ISPK", "0");
            rf.set("RESOURCEFIELD_FIELDLAZY", "0");
            rf.set("RESOURCEFIELD_DESCRIPTION", "");
            rf.set("SY_FLAG", "1");
            commonService.buildModelCreateInfo(rf);
            metaService.insert(rf);
        }
        return BaseRespResult.successResult(null, "添加成功");
    }

    /**
     * @param param
     */
    @RequestMapping(value = "doUpdate", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doUpdate(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        String tableCode = param.getTableCode();
        DynaBean oldColumn = metaService.selectOneByPk(tableCode, dynaBean.getStr("JE_CORE_RESOURCECOLUMN_ID"));
        commonService.buildModelModifyInfo(dynaBean);
        metaService.update(dynaBean);
        funcRelyonService.doUpdate("JE_CORE_RESOURCECOLUMN", dynaBean.getStr("RESOURCECOLUMN_FUNCINFO_ID"), funcRelyonService.getUpdateBean("JE_CORE_RESOURCECOLUMN", dynaBean, oldColumn));
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * @param param
     */
    @RequestMapping(value = "doRemove", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @Override
    public BaseRespResult doRemove(BaseMethodArgument param, HttpServletRequest request) {
        String ids = param.getIds();
        param.setTableCode("JE_CORE_RESOURCECOLUMN");
        funcRelyonService.doRemove("JE_CORE_RESOURCECOLUMN", null, ids, null);
        int delNum = resColumnService.doRemove(ids);
        return BaseRespResult.successResult(delNum + "条记录被删除!");
    }

    /**
     * @param param
     */
    @RequestMapping(value = "getTreeTableCodes", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public JSONArray getTreeTableCodes(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        DynaBean funcInfo = metaService.selectOneByPk("JE_CORE_FUNCINFO", dynaBean.getStr("JE_CORE_FUNCINFO_ID"), "FUNCINFO_FUNCDICCONFIG,FUNCINFO_TABLENAME,FUNCINFO_PKNAME,JE_CORE_FUNCINFO_ID");
        List<String> treeCodes = resColumnService.getTreeTableCodes(funcInfo);
        return DirectJsonResult.buildArrayResult(treeCodes);
    }

}
